﻿package igz.fleaxy.library {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.ProgressEvent;
	import igz.fleaxy.events.CommEvent;
	import igz.fleaxy.net.Comm;
	import igz.fleaxy.util.ImageUtil;
	import igz.fleaxy.util.ObjectUtil;
	/**
	 * ...
	 * @author Intelygenz | www.intelygenz.com
	 */
	public class Library {

		protected var _Settings:Object = { "onComplete" : null
		, "onProgress" : null
		, "onCompleteParams" : null
		}
		
		protected var _MovieClip:MovieClip;

		public function $Get(p_instanceName:String) : DisplayObject {
			if ( _MovieClip!=null && _MovieClip.hasOwnProperty(p_instanceName) ) {
				return _MovieClip[p_instanceName] as DisplayObject;
			}
			else {
				if ( _MovieClip == null ) {
					trace("Library.$Get(" + p_instanceName + ") :: No se ha cargado ninguna librería");
				}
				else if (_MovieClip.hasOwnProperty(p_instanceName)) {
					trace("Library.$Get(" + p_instanceName + ") :: No existe ninguna instancia con ese identificador en la librería cargada");
				}
				return null;
			}
		}
		
		public function $GetBitmap ( p_instanceName:String ) : Bitmap {
			return ImageUtil.$GetBitmap( $Get( p_instanceName ) );
		}
		
		public function $GetBitmapData ( p_instanceName:String ) : BitmapData {
			return ImageUtil.$GetBitmapData( $Get( p_instanceName ) );
		}

		/**
		 *
		 * @param	p_uri : String
		 * @param	p_settings: { "onComplete" : function
								, "onProgress" : function
								, "onCompleteParams" : Object
								}
		 */
		public function $Load( p_uri:String, p_settings:Object ) : void {
			ObjectUtil.$Merge(p_settings, _Settings);
			Comm.$LoadFile( p_uri, { "onComplete" : _LoadFile_OnComplete
								   , "onProgress" : _LoadFile_OnProgress
								   , "onCompleteParams" : _Settings["onCompleteParams"]
								   }
						  );
		}

		private function _LoadFile_OnComplete( p_commEvent:CommEvent ) : void {
			_MovieClip = p_commEvent.$ResponseSwf as MovieClip;
			if ( _Settings.hasOwnProperty("onComplete") && _Settings["onComplete"] != null ) {
				if ( p_commEvent.$Params!=null ) {
					_Settings["onComplete"](p_commEvent.$Params);
				}
				else {
					_Settings["onComplete"]();
				}
			}
		}

		private function _LoadFile_OnProgress( p_progressEvent:ProgressEvent ) : void {
			if ( _Settings.hasOwnProperty("onProgress") && _Settings["onProgress"]!=null ) {
				_Settings["onProgress"](p_progressEvent);
			}
		}
	}

}